﻿using System;
using System.Data;
using System.Web;

using Discuz.Common;
using Discuz.Common.Generic;
using Discuz.Forum;
using Discuz.Web.UI;
using Discuz.Config;
using Discuz.Entity;

namespace Discuz.Web
{
    /// <summary>
    /// showforum 的摘要说明.
    /// </summary>
    public class showtree : Discuz.Web.UI.TopicPage
    {
        #region 页面变量
        /// <summary>
        /// 主题所属帖子
        /// </summary>
        public ShowtopicPagePostInfo post;
        /// <summary>
        /// 投票选项列表
        /// </summary>
        public DataTable polloptionlist;
        /// <summary>
        /// 投票帖类型
        /// </summary>
        public PollInfo pollinfo;
        /// <summary>
        /// 是否显示投票结果
        /// </summary>
        public bool showpollresult = true;
        /// <summary>
        /// 短消息列表
        /// </summary>
        public List<PrivateMessageInfo> pmlist = new List<PrivateMessageInfo>();
        /// <summary>
        /// 悬赏给分日志
        /// </summary>
        public List<BonusLogInfo> bonuslogs;
        /// <summary>
        /// 主题回复列表
        /// </summary>
        public DataTable posttree;
        /// <summary>
        /// 帖子Id
        /// </summary>
        public int postid = DNTRequest.GetInt("postid", -1);
        /// <summary>
        /// 是否是投票帖
        /// </summary>
        public bool ispoll = false;
        /// <summary>
        /// 积分策略信息
        /// </summary>
        public UserExtcreditsInfo userextcreditsinfo;
        #endregion


		protected override void ShowPage()
		{
            ismoder = Moderators.IsModer(useradminid, userid, forumid) ? 1 : 0;
            topic = GetTopicInfo();
            if (IsErr())
                return;       
           
            forumid = topic.Fid;
            forum = Forums.GetForumInfo(forumid);
            if (forum == null)
            {
                AddErrLine("不存在的版块ID"); return;
            }
            // 检查是否具有版主的身份
            if (useradminid != 0)
            {
                ismoder = Moderators.IsModer(useradminid, userid, forum.Fid) ? 1 : 0;
                admininfo = AdminGroups.GetAdminGroupInfo(usergroupid); //得到管理组信息
                if (admininfo != null)
                    disablepostctrl = admininfo.Disablepostctrl;
            }
            //验证版块密码
            if (!ValidateForumPassword()) 
                return;

            #region 
            GetForumAds(forum.Fid);
            //快速编辑器背景广告
            quickbgad = Advertisements.GetQuickEditorBgAd("", forumid);
            if (quickbgad.Length <= 1)
                quickbgad = new string[2] { "", "" };
            #endregion

            enabletag = (config.Enabletag & forum.Allowtag) == 1;
            pagetitle = string.Format("{0} - {1}", topic.Title, forum.Name);
            smileyoff = 1 - forum.Allowsmilies;
            if (forum.Allowbbcode == 1 && usergroupinfo.Allowcusbbcode == 1)
                bbcodeoff = 0;

            // 权限认证，包括回复，下载附件，发主题等
            if (!ValidateAuthority())
                return;

            //获取主题类型
            Caches.GetTopicTypeArray().TryGetValue(topic.Typeid, out topictypes);
            topictypes = Utils.StrIsNullOrEmpty(topictypes) ? "" : "[" + topictypes + "]";

            userextcreditsinfo = Scoresets.GetScoreSet(Scoresets.GetCreditsTrans());
            score = Scoresets.GetValidScoreName();
            scoreunit = Scoresets.GetValidScoreUnit();

            //购买帖子操作, 判断是否为回复可见帖, price=0为非购买可见(正常), price>0 为购买可见, price=-1为购买可见但当前用户已购买
            int price = GetTopicPrice(topic);
            if (topic.Special == 0 && price > 0)
            {
                HttpContext.Current.Response.Redirect(forumpath + "buytopic.aspx?topicid=" + topic.Tid); return;
            }

            if (newpmcount > 0)
                pmlist = PrivateMessages.GetPrivateMessageListForIndex(userid, 5, 1, 1);

            PostpramsInfo postpramsInfo = GetPostPramsInfo(price);

            if (topic.Special == 1)//获取投票信息
                GetPollInfo();

            bonuslogs = Bonus.GetLogs(topic);

            post = Posts.GetSinglePost(postpramsInfo, out attachmentlist, ismoder == 1);

            if (post == null)
            {
                AddErrLine("读取信息失败"); return;
            }

            posttree = Posts.GetPostTree(topicid, postpramsInfo.Hide, Users.GetUserInfo(userid).Credits);

            //更新查看次数
            TopicStats.Track(topic.Tid, 1);
            topicviews = topic.Views + 1;
            OnlineUsers.UpdateAction(olid, UserAction.ShowTopic.ActionID, forum.Fid, forum.Name, topic.Tid, topic.Title.Trim(), config.Onlinetimeout);
        }

        /// <summary>
        /// 获取主题信息
        /// </summary>
        /// <returns></returns>
        public new TopicInfo GetTopicInfo()
        {
            // 如果主题ID非数字则判断帖子ID，或只有主题id则获取主题的第一个帖子的内容
            if (topicid != -1 && postid == -1)
                postid = Posts.GetFirstPostId(topicid);

            PostInfo __postinfo = Posts.GetPostInfo(topicid, postid);
            if (__postinfo == null)
            {
                AddErrLine("错误的主题");
                return null;
            }
            else if (topicid == -1)
                topicid = __postinfo.Tid;

            if (topicid != __postinfo.Tid)
            {
                AddErrLine("主题ID无效");
                return null;
            }

            // 获取该主题的信息
            TopicInfo topicInfo = Topics.GetTopicInfo(topicid);
            // 如果该主题不存在
            if (topicInfo == null)
            {
                AddErrLine("不存在的主题ID");
                return null;
            }

            if (topicInfo.Displayorder == -1)
                AddErrLine("此主题已被删除！");

            if (topicInfo.Displayorder == -2)
                AddErrLine("此主题未经审核！");

            if (topicInfo.Identify > 0)
            {
                topicidentify = Caches.GetTopicIdentify(topicInfo.Identify);
                //原来的鉴定项已被移除，则将其恢复成未被鉴定的主题
                if (topic.Identify != topicidentify.Identifyid)
                    TopicAdmins.IdentifyTopic(topicid.ToString(), 0);
            }
            if (topicInfo.Readperm > usergroupinfo.Readaccess && topicInfo.Posterid != userid && useradminid != 1 && ismoder == 0)
            {
                AddErrLine("本主题阅读权限为: " + topicInfo.Readperm + ", 您当前的身份 \"" + usergroupinfo.Grouptitle + "\" 阅读权限不够");
                if (userid == -1)
                    needlogin = true;
            }
            GetForumAds(0);
            return topicInfo;
        }

        /// <summary>
        /// 获取帖子参数信息(PostPramsInfo)
        /// </summary>
        /// <param name="price"></param>
        /// <returns></returns>
        public PostpramsInfo GetPostPramsInfo(int price)
        {
            PostpramsInfo postpramsInfo = new PostpramsInfo();
            postpramsInfo.Fid = forum.Fid;
            postpramsInfo.Tid = topicid;
            postpramsInfo.Pid = postid;
            postpramsInfo.Jammer = forum.Jammer;
            postpramsInfo.Pagesize = ppp;     // 得到Ppp设置
            postpramsInfo.Pageindex = pageid;
            postpramsInfo.Getattachperm = forum.Getattachperm;
            postpramsInfo.Usergroupid = usergroupid;
            postpramsInfo.Attachimgpost = config.Attachimgpost;
            postpramsInfo.Showattachmentpath = config.Showattachmentpath;
            postpramsInfo.Price = price;
            postpramsInfo.Bbcodemode = config.Bbcodemode;
            postpramsInfo.Ubbmode = false;
            postpramsInfo.Topicinfo = topic;
            postpramsInfo.Usergroupreadaccess = (ismoder == 1) ? int.MaxValue : usergroupinfo.Readaccess;
            postpramsInfo.CurrentUserid = userid;
            postpramsInfo.CurrentUserGroup = usergroupinfo;
            postpramsInfo.Showimages = forum.Allowimgcode;
            postpramsInfo.Smiliesinfo = Smilies.GetSmiliesListWithInfo();
            postpramsInfo.Customeditorbuttoninfo = Editors.GetCustomEditButtonListWithInfo();
            postpramsInfo.Smiliesmax = config.Smiliesmax;
            //判断是否为回复可见帖, hide=0为不解析[hide]标签, hide>0解析为回复可见字样, hide=-1解析为以下内容回复可见字样显示真实内容
            //将逻辑判断放入取列表的循环中处理,此处只做是否为回复人的判断，主题作者也该可见
            postpramsInfo.Hide = (topic.Hide == 1 && (Posts.IsReplier(topicid, userid) || ismoder == 1)) ? -1 : 1;
            postpramsInfo.Hide = topic.Posterid == userid ? -2 : postpramsInfo.Hide;
            postpramsInfo.TemplateWidth = Templates.GetTemplateWidth(templatepath);//获取当前模版的宽度

            return postpramsInfo;
        }

        /// <summary>
        /// 获取主题价格
        /// </summary>
        /// <param name="topicInfo"></param>
        /// <returns></returns>
        public int GetTopicPrice(TopicInfo topicInfo)
        {
            int price = 0;
            if (topicInfo.Special == 0)//普通主题
            {
                //购买帖子操作
                //判断是否为购买可见帖, price=0为非购买可见(正常), price>0 为购买可见, price=-1为购买可见但当前用户已购买                
                if (topicInfo.Price > 0 && userid != topicInfo.Posterid && ismoder != 1)
                {
                    price = topicInfo.Price;
                    //时间乘以-1是因为当Configs.GetMaxChargeSpan()==0时,帖子始终为购买帖
                    if (PaymentLogs.IsBuyer(topicInfo.Tid, userid) ||
                        (Utils.StrDateDiffHours(topicInfo.Postdatetime, Scoresets.GetMaxChargeSpan()) > 0 &&
                         Scoresets.GetMaxChargeSpan() != 0)) //判断当前用户是否已经购买
                    {
                        price = -1;
                    }
                }
            }
            return price;
        }

        /// <summary>
        /// 获取投票信息
        /// </summary>
        public void GetPollInfo()
        {
            pollinfo = Polls.GetPollInfo(topicid);
            voters = Polls.GetVoters(topicid, userid, username, out allowvote);

            if (pollinfo.Uid != userid && useradminid != 1) //当前用户不是投票发起人或不是管理组成员
            {
                if (pollinfo.Visible == 1 && //当为投票才可见时
                (allowvote || (userid == -1 && !Utils.InArray(topicid.ToString(), ForumUtils.GetCookie("dnt_polled")))))//当允许投票或为游客(且并未投过票时)时
                {
                    showpollresult = false;
                }
            }


            if (Utils.StrIsNullOrEmpty(pollinfo.Expiration))
                pollinfo.Expiration = DateTime.Now.ToString();

            if (DateTime.Parse(pollinfo.Expiration) < DateTime.Now)
                allowvote = false;
        }

    }
}
